/**
 * Administrator
 * 2011-3-7
 * TODO
 */
package hc.trip.airticket.result;

import hc.trip.airticket.bean.FlightInfo;
import hc.trip.airticket.bean.PriceInfo;
import hc.trip.airticket.bean.QueryInfo;
import hc.trip.airticket.bean.ResultInfo;
import hc.trip.airticket.constant.StaticParameter;
import hc.trip.airticket.httpclient.HttpRequestProxy;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.ConnectTimeoutException;

/**深圳航空 
 * @author 0707
 * @date 2011-3-7
 * @description TODO
 */
public class GetFlightListZH {
	/**
	 * 根据航班的查询条件（出发城市、到达城市、时间）请求并分析得到结果集合
	 * @param queryInfo
	 * @return
	 * @throws Exception
	 */
		public ResultInfo getResultInfo(QueryInfo queryInfo){
			
			String responseText = "";
			ResultInfo resultInfo = null;
			//查询条件不合法
			if(queryInfo==null||queryInfo.getDateString()==null||queryInfo.getDateString().length()<=0||queryInfo.getDesCity()==null||queryInfo.getDesCity().length()<=0||queryInfo.getOrgCity()==null||queryInfo.getOrgCity().length()<=0){
				return null;
			}
			
			HttpRequestProxy proxy = new HttpRequestProxy();
			Map postData   = new HashMap();
			Map header     = new HashMap();
			
			//请求头部
			header.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 1.7; .NET CLR 1.1.4322; CIBA; .NET CLR 2.0.50727)");
		    header.put("Host", "www.shenzhenair.com");
		    header.put("Referer", "http://www.shenzhenair.com/common/flightSearch.do");
 
			postData.put("flightConditionEntity.hcType", "DC");  //单程
			postData.put("originalPage", "index");  //  从主页中查询
			postData.put("orgCity10", queryInfo.getOrgCity());  //出发 
			postData.put("flightConditionEntity.dstCity0", queryInfo.getDesCity());  //到达
		 
			postData.put("orgDate10", queryInfo.getDateString());  //出发日期
			postData.put("operate", "flightSearch");
 
			//postData.put("strIdentity", "1300115404626ankwsmlanhkyqpwplxv");
			try { 
				responseText = proxy.doRequest(
		 	    "http://www.shenzhenair.com/common/flightSearch.do", postData, header,"GBK");
			 
				resultInfo = (ResultInfo)analyzeResopnseText(responseText);
				}
		        catch (ConnectTimeoutException e) {   //超时
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusTimeOut);   
				e.printStackTrace();
			} 
		        catch (Exception e) {                //其他异常
				// TODO: handle exception
				if (resultInfo==null) {
					resultInfo = new ResultInfo();
				}
				resultInfo.setStatus(StaticParameter.analyzeStatusError);
				e.printStackTrace();
			}
		  	return resultInfo;
}
	
		
		/**
		 * 根据深圳航空网站返回的responseText通过正则表达式分析出结果
		 * @param source  返回的responseText
		 * @return        结果列表 
		 * @throws Exception 
		 */
		public ResultInfo analyzeResopnseText(String source) throws Exception{
		      PriceInfo priceInfo = null;
		      List priceList  =  null;
		      ResultInfo resultInfo = new ResultInfo();  //结果对象

		      if (source==null||source.trim().length()==0) {
				return null;
			}
	 		  String[] parts = source.split("<div\\s*id=\"flightInfoa\\d{1,3}\"\\s*style=\"display:none;\"\\s*>"); //将每一个航班区分开来
 
 
	 		  if (parts.length==0) {     //没有航班信息
				System.out.println("深圳航空没有相应航班信息------------------------------");
				return null;
			}
 
			     ArrayList<FlightInfo> flightInfos = new ArrayList<FlightInfo>();  //存放所有的航班信息
			     

			     StringBuffer regexSB = new StringBuffer();  //匹配航班信息
			    
			     regexSB.append("<tr\\s*bordercolor=\"#ffffff\">\\s*<td style=\"border-bottom-color:#E6E6E6\">(&nbsp)+机型:(.*?)(&nbsp){1,}经停:(.*?)</td>\\s*</tr>");  //机型 （2）& 经停（4） 
			     regexSB.append(".*?承运：\\s*<b>\\w{1,3}</b>(&nbsp){1,}<b>.*?</b>(&nbsp){1,}\\s*<b>(.*?)</b>.*?"); //共享航班  7
			   //   承运：<b>ZH</b>&nbsp&nbsp<b>未知</b>&nbsp&nbsp <b>ZH</b>
 
			       regexSB.append("<tr\\s*id=\"trFlightInfo\\d{1,}\">\\s*<td\\s*width=\"10%\"\\s*class=\"bk\"\\s*align=\"center\"\\s*bgcolor=\"#FFFFFF\"\\s*style=\"border-right-color:#FFFFFF\\s*\"><span\\s*class=\"sy\">(.*?)</span>.*?");  //航班号    代码共享的标志
			      regexSB.append("\\s*</td>\\s*<td\\s*width=\"10%\"\\s*class=\"bk\"\\s*bgcolor=\"#FFFFFF\"\\s*style=\"border-right-color:#FFFFFF;border-left-color:#FFFFFF\\s*\">\\s*<table width=\"100%\"\\s*border=\"0\"\\s*cellspacing=\"0\"\\s*cellpadding=\"0\">\\s*<tr>\\s*");
			     regexSB.append("<td\\s*valign=\"middle\"\\s*class=\"sy\"\\s*align=\"center\">(.*?)</td>\\s*</tr>\\s*<tr>\\s*<td\\s*class=\"sy\"\\s*align=\"center\">(.*?)</td>\\s*</tr>");  //起飞时间、降落时间
			     
 
			     
			     //航班号  ，航班号+代码共享 ，出发时间，降落时间。
			     String regex =regexSB.toString();
 
			    
			     Pattern p = Pattern.compile(regex,Pattern.CASE_INSENSITIVE);
			     

			     FlightInfo tempInfo = null;
			     double  tempMinPriceForAll = 0.0;  //所有航班的最低价格
			     double  tempMaxPriceForAll = 0.0;  //所有航班的最高价格
			     boolean tempIsFirstForAll = true;
			 
			     //依次取出每个航班的信息,因为parts[0]中没有航班信息，所以数组下标从1开始
 		     	 for(int j=1;j<parts.length;j++){
 				 priceList  =  new ArrayList();
 				 tempInfo =new FlightInfo();
 				 //System.out.println(parts[j]);
			     Matcher matcher = p.matcher(parts[j]);
//		if (matcher.find()) {
//			System.out.println("第几次咧"+j);
//			     for (int i = 1; i <= matcher.groupCount(); i++) {
//					System.out.println("group"+i+" : "+matcher.group(i));
//					 
//				}}
//			     if (true) {
//					continue;
//				}
			     if(matcher.find())   //匹配航班信息
			     {	    	 
 
			    	 String flightNo = matcher.group(8).trim();
			    	 String flightNoAndShareCode = matcher.group(7).trim();
			    	 tempInfo.setFlightNo(flightNo);  //航班号
			    	//判断是否是代码共享
			    	 if(flightNoAndShareCode!=null&&flightNoAndShareCode.length()>0&&!flightNoAndShareCode.equalsIgnoreCase("ZH")){  //如果flightNoAndShareCode有内容，则是代码共享航班
 
			    			 tempInfo.setShareCodeFlag(true);
			    			 tempInfo.setShareCode(flightNoAndShareCode); 
			    	 
			    	 }
			    	 //判断代码共享结束
			    	 
			    	 //判断是否经停  值有三种：1.无 2.未知 3.具体经停城市
                    String isStopOver = matcher.group(4).trim();
                    if (isStopOver!=null&&isStopOver.length()>0) {
                    	if (!isStopOver.equals("无")&&!isStopOver.equals("未知")) {  //如果有具体的经停城市
							tempInfo.setStopOver(true);
						}
					}
			    	//判断经停结束 
                    
			     
			    	 String takeOffTimeString = matcher.group(9).trim();
			    	 String arriveTimeString = matcher.group(10).trim();
			    	 if (takeOffTimeString==null||takeOffTimeString.length()==0||arriveTimeString==null||arriveTimeString.length()==0) {
						System.out.println("深圳航空分析不正确");
						return null;
					}
			    	 tempInfo.setTakeOffTime(takeOffTimeString.split(":")[1]+":"+takeOffTimeString.split(":")[2]);
			    	 tempInfo.setArriveTime( arriveTimeString.split(":")[1]+":"+arriveTimeString.split(":")[2]);
			    	 tempInfo.setPlaneType(matcher.group(2).trim());   //机型
 
			     }else {
					System.out.println("没有匹配到航班。。。。");
				}
			       //分析价格start
		    	 double tempMinPrice = 0.0;
		    	 double tempMaxPrice = 0.0;
		    	 boolean isFirst = true;
		    	 //如果是代码共享航班，则头等舱的价格匹配为共享航班号
		    	  String flightNoString = tempInfo.isShareCodeFlag()?tempInfo.getShareCode().trim():tempInfo.getFlightNo().trim();
			      //单独分析头等舱的价格
			      String   fCabinRegex = "<input type=\"radio\"\\s*name=\"radioButton0\"\\s*onClick=\"cancelFlightprice().*?codeShareMark=\".*?\"\\s*messages=\".*?&"+flightNoString+"&F&(.*?)&头等舱&.*?&firstClass\"\\s*id=\"radioFirstClass\""; 
			     
			      Pattern  fCabinPattern = Pattern.compile(fCabinRegex);
			      Matcher  fMatcher = fCabinPattern.matcher(parts[j]);
			      tempInfo.setHaveSeat(false);
			     if (fMatcher.find()) {
			    	 priceInfo  =  new PriceInfo();
			    	 priceInfo.setSpace("F");
			    	 priceInfo.setPrice(Double.parseDouble(fMatcher.group(2).trim().split("&")[1]));
			    	 priceList.add(priceInfo);
			    	 
			    	 tempInfo.setHaveSeat(true);   //如果有价格就认为是有座或者有效航班
			    	  //一个航班不同cabin的最低和最高价格获取
			    	  if (isFirst) {
			    		  tempMinPrice = priceInfo.getPrice();
			    		  tempMaxPrice = priceInfo.getPrice();
			    		  tempInfo.setMinprice(tempMinPrice);
			    		  tempInfo.setMaxprice(tempMaxPrice);
			    		  isFirst = false;
					}
			    	 
					     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
					    	 tempMinPrice = priceInfo.getPrice();
							}
					     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
					    	 tempMaxPrice = priceInfo.getPrice(); 
						}
					     tempInfo.setMaxprice(tempMaxPrice);
					     tempInfo.setMinprice(tempMinPrice);
				}
			     //开始分析其他舱的价格
			     String otherCabinRegex = "<select name=\"selectClassList\" onChange=\"classChanged.*?style=\"font-family:Arial;width:75px;\">(.*?)</select>";
			     Pattern otherCabinPattern = Pattern.compile(otherCabinRegex) ;
			     Matcher otherCabinMatcher = otherCabinPattern.matcher(parts[j]);
			     if (otherCabinMatcher.find()) {
					 String otherCabinSource = otherCabinMatcher.group(1).trim();   //其他舱位开始匹配
				     String priceRegex = "<option\\s*value=\\s*'(.*?)'>.*?</option>";
				     Pattern pPrice = Pattern.compile(priceRegex,Pattern.CASE_INSENSITIVE);
				     Matcher mPrice = pPrice.matcher(parts[j]);
				     
				     while (mPrice.find()) {
				    	 priceInfo  =  new PriceInfo();
				    	 
						 String[] temp  = mPrice.group(1).trim().split(";");
						 priceInfo.setPrice(Double.parseDouble(temp[2]));
						 priceInfo.setSpace(temp[9]);
						 priceList.add(priceInfo);
						 
						 tempInfo.setHaveSeat(true);   //如果有价格就认为是有座或者有效航班
						 
						  //一个航班不同cabin的最低和最高价格获取
				    	  if (isFirst) {
				    		  tempMinPrice = priceInfo.getPrice();
				    		  tempMaxPrice = priceInfo.getPrice();
				    		  tempInfo.setMinprice(tempMinPrice);
				    		  tempInfo.setMaxprice(tempMaxPrice);
				    		  isFirst = false;
						}
				    	 
						     if (tempMinPrice>priceInfo.getPrice()) {   //如果一个航班的tempMinPrice不是最低价格
						    	 tempMinPrice = priceInfo.getPrice();
								}
						     if (tempMaxPrice<priceInfo.getPrice()) {   //如果一个航班的tempMaxPrice不是最高价格
						    	 tempMaxPrice = priceInfo.getPrice(); 
							}
						     tempInfo.setMaxprice(tempMaxPrice);
						     tempInfo.setMinprice(tempMinPrice);
					}
					 
				}
			   
			     //开始分析‘最低价’的信息
			     StringBuffer lowestCabinRegex =new StringBuffer();
			     lowestCabinRegex.append("<input type=\"radio\" name=\"radioButton0\" onClick=\"cancelFlightprice.*?;\" codeShareMark=\".*?\" messages=\".*?&online.*?&.*?&(.*?)&.*?\"\\s*id=\"radioListOnline.*?\"");
			     lowestCabinRegex.append(".*?12px;font-weight: normal;font-weight:bold;\">\\s*<label\\s*id=\".*?\"\\s*>(.*?)</label>\\s*</font>");
			     Pattern lowestCabinPattern  = Pattern.compile(lowestCabinRegex.toString());
			     Matcher lowestCabinMatcher  = lowestCabinPattern.matcher(parts[j]);
			     PriceInfo tempInfo2  = null;
			     if (lowestCabinMatcher.find()) {
					String cabin  = lowestCabinMatcher.group(1).trim();
					String price = lowestCabinMatcher.group(2).trim().replace("￥","").trim();
					Double pricedDouble = Double.parseDouble(price);
					if (priceList!=null&&priceList.size()>0) {
					Iterator iterator = priceList.iterator();
					while (iterator.hasNext()) {
						   tempInfo2 = (PriceInfo)iterator.next();
						 if (tempInfo2.getSpace().equalsIgnoreCase(cabin)) {
							if (tempInfo2.getPrice()>pricedDouble) {
								tempInfo2.setPrice(pricedDouble);
								 
							}
						}
					}
					   if (tempMinPrice>pricedDouble) {   //如果一个航班的tempMinPrice不是最低价格
					    	 tempMinPrice = pricedDouble;
							}
					     if (tempMaxPrice<pricedDouble) {   //如果一个航班的tempMaxPrice不是最高价格
					    	 tempMaxPrice = pricedDouble; 
						}
					
			     }else {
			    	   tempInfo2 = new PriceInfo();
			    	   tempInfo2.setPrice(Double.parseDouble(price));
			    	   tempInfo2.setSpace(cabin);
			    	   priceList.add(tempInfo2);
			    	   tempMinPrice = pricedDouble;
			    	   tempMaxPrice = pricedDouble;
				}
					 
					     tempInfo.setMaxprice(tempMaxPrice);
					     tempInfo.setMinprice(tempMinPrice);
				}
			     
 
			     tempInfo.setPrice(priceList);
			     flightInfos.add(tempInfo);
			     
			     //在每一个航班的循环内，取得目前航班中的最低价格和最高价格
			     if (tempIsFirstForAll&&tempInfo.isHaveSeat()) {      //初始值
			    	 tempMinPriceForAll = tempInfo.getMinprice();
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
			    	 tempIsFirstForAll  = false;
				}
			     if (tempMinPriceForAll>tempInfo.getMinprice()&&tempInfo.isHaveSeat()) {   
 
			    	 tempMinPriceForAll = tempInfo.getMinprice();
				}
			     if (tempMaxPriceForAll<tempInfo.getMaxprice()&&tempInfo.isHaveSeat()) {
				 
			    	 tempMaxPriceForAll = tempInfo.getMaxprice();
				}
		    	 resultInfo.setMinPriceFlight(tempMinPriceForAll);
		    	 resultInfo.setMaxPriceFlight(tempMaxPriceForAll);
			     
 		     	 }
 		    resultInfo.setResultList(flightInfos);	  
 		 	 
			return resultInfo;
		}

		
		
}
